import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"

// 引入组件
import Login from "@/views/Login.vue"
import Posts from "@/views/Posts.vue"

// 定义路由
const routes: Array<RouteRecordRaw> = [
    // 重定向根路径到登录页
    {
        path: "/",
        redirect: "/posts"
    },
    // 登录页面
    {
        name: "Login",
        path: "/login",
        component: Login,
        meta: {
            title: "用户登录",
            description: "请登录您的账户",
            requestAuth: false,
            layout: "auth",
            keepAlive: false
        }
    },
    // 帖子列表页面
    {
        name: "Posts",
        path: "/posts",
        component: Posts,
        meta: {
            title: "社区动态",
            description: "查看和互动社区帖子",
            requestAuth: true,
            layout: "main",
            keepAlive: true,
            breadcrumb: [
                { name: "首页", path: "/posts" },
                { name: "社区动态", path: "/posts" }
            ]
        }
    },
]

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 路由守卫
router.beforeEach((to, _from, next) => {
    next()
    // // 设置页面标题
    // if (to.meta.title) {
    //     document.title = `${to.meta.title} - Vue社区`
    // }

    // // 检查是否需要登录
    // const isLoginRequired = to.meta.requestAuth === true
    // const userInfo = localStorage.getItem('userInfo')

    // if (isLoginRequired && !userInfo) {
    //     // 需要登录但未登录，重定向到登录页
    //     next({
    //         name: 'Login',
    //         query: { redirect: to.fullPath }
    //     })
    // } else if (to.name === 'Login' && userInfo) {
    //     // 已登录用户访问登录页，重定向到首页
    //     next({ name: 'Posts' })
    // } else {
    //     // 正常访问
    //     next()
    // }
})

export default router